package com.killer.TimeTask;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.killer.enums.TaskStatus;
import com.killer.mq.Constant;
import com.killer.pojo.entity.Message;
import com.killer.service.MessageService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class TimeTaskHandler {


    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private MessageService messageService;


    private final Integer TIME_OUT = 10000;


    @XxlJob("demoJobHandler")
    public void demoJobHandler() throws Exception {
        System.out.println("hello world");
        // default success
    }

    //判断为正确发送的消息
    @XxlJob("taskJobHandler")
    public void taskJobHandler() throws Exception{
        List<Message> messages = messageService.list();
        for(int i = 0;i < messages.size();i++){
            //扫描如果重试次数大于 三次且状态为创建中
            Message message = messages.get(i);
            int curState = message.getStatus();
            if(message.getRetryTimes() > 3 && message.getStatus() == TaskStatus.CREATE.getKey()){
               rocketMQTemplate.asyncSend(Constant.topic, messages, new SendCallback() {
                   @Override
                   public void onSuccess(SendResult sendResult) {
                       if(sendResult.getSendStatus() != SendStatus.SEND_OK){
                           //使用乐观锁更新状态
                          convertStatusToFailed(message,curState);
                       }
                   }
                   @Override
                   public void onException(Throwable throwable) {
                       convertStatusToFailed(message,curState);
                   }
               });
            }
        }
    }


    //判断导出超时的消息
    @XxlJob("timeOutHandler")
    public void timeOutHandler() throws Exception{
        List<Message> messages = messageService.list();
        for(int i = 0;i < messages.size();i++){
            Message message = messages.get(i);
            Date date = new Date();
            //假如任务一直卡在导出中且超时
            if(message.getStatus() == TaskStatus.EXPORT.getKey() && date.getTime() - message.getCreateTime().getTime() > TIME_OUT ){
                convertStatusToFailed(message,message.getStatus());
            }
        }
    }


    protected void convertStatusToFailed(Message message,int curState){
        int num = curState == TaskStatus.CREATE.getKey() ? TaskStatus.FAILED.getKey() - TaskStatus.CREATE.getKey() :
                TaskStatus.FINISH.getKey() - TaskStatus.EXPORT.getKey();
        UpdateWrapper<Message> updateWrapper = new UpdateWrapper<>();
        //version换成状态机
        updateWrapper.eq("state", curState);
        updateWrapper.eq("id", message.getId());
        Message msg = new Message();
        msg.setIsConsumer(1);
        msg.setStatus(curState + num);
        messageService.update(msg,updateWrapper);
    }







}
